import { CaretLeftFilled, CaretRightFilled } from '@ant-design/icons'
import { Layout, Spin } from 'antd'
import { connect } from 'dva'
import { lazy, useState } from 'react'

import { routesMap } from '@/router/index'
import { modal } from '@/utils/antdHelper'
import { getBasicFn } from '@/utils/dvaUtil/index'

import styles from './index.module.less'

const Page404 = lazy(() => import('@/components/Page404'))
const Header = lazy(() => import('./components/Header'))
const Aside = lazy(() => import('./components/Aside'))
const TopMenu = lazy(() => import('./components/TopMenu'))

const namespace = 'app'

/**
 * 处理头部菜单和左侧菜单的组件
 * @param {Object} param0
 * @param {import('@/models/app').state} param0.app
 * @param {import('@/models/app/notice').state} param0.notice
 * @returns
 */
const App = ({ app, notice, loading, children, location }) => {
  const { getLoading, toAction } = getBasicFn({
    namespace,
    loading,
  })
  const { pathname } = location
  const { isLogin } = app
  const { firstInactivePlayAudio } = notice

  const [collapsed, setCollapsed] = useState(false) // 侧边菜单收缩

  const paths = pathname.split('/')
  const pageKey = paths.pop()

  let page404 = undefined
  // 不在系统的路由中
  if (!routesMap[pageKey]) {
    page404 = <Page404 />
  }

  const firstEnableInactivePlayAudio = () => {
    if (firstInactivePlayAudio) return
    toAction('notice/updateState', { firstInactivePlayAudio: true })
    const au = document.getElementById('J-zmx-notice')
    au.muted = true
    au.play().catch(() => {
      modal.confirm({
        icon: null,
        content: '系统消息通知需要开启',
        cancelButtonProps: { style: { display: 'none' } },
        onOk: au.play,
      })
    })
  }

  return (
    <Spin spinning={getLoading('silentLogin', 'beforOpenPage')}>
      <div className={styles.app} onClick={firstEnableInactivePlayAudio}>
        <Header />
        <Layout className={styles.layout}>
          <Layout.Sider theme='light' width={168} collapsed={collapsed} collapsible collapsedWidth={80} trigger={null}>
            <Aside {...{ collapsed, pathname }} />
            <div
              className={styles.siderTigger}
              onClick={() => {
                setCollapsed(!collapsed)
              }}
            >
              {collapsed ? <CaretRightFilled /> : <CaretLeftFilled />}
            </div>
          </Layout.Sider>
          <Layout.Content className={styles.content}>
            {isLogin && (
              <>
                <TopMenu {...{ location }} />
                {page404 || children}
              </>
            )}
          </Layout.Content>
        </Layout>
      </div>
    </Spin>
  )
}

export default connect(({ app, notice, loading }) => ({
  app,
  notice,
  loading,
}))(App)
